package fluo.http;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import java.io.*;
import java.net.URI;
import java.net.URLDecoder;

import sun.net.www.protocol.http.HttpURLConnection;
public class HttpServerHandler implements HttpHandler  
{
	byte[] mp3;
	public void handle(HttpExchange httpExchange) throws IOException
	{
		buildResponse(httpExchange.getRequestURI());
		System.out.println(httpExchange.getRequestURI());
		httpExchange.getResponseHeaders().add("Content-Type","audio/mpeg");
		String size = mp3.length + "";
		httpExchange.getResponseHeaders().add("Content-Length",size);
		httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, mp3.length);
		OutputStream os = httpExchange.getResponseBody();
		os.write(mp3);
		mp3 = null;
		os.close();
	}

	/**
	 * Build a String to return to the web browser via an HTTP response.
	 * 
	 * @return String for HTTP response.
	 */
	private void buildResponse(URI uri)
	{
		DataInputStream buffer;

		try
		{
			
			String decodedString = uri.getRawPath().replaceAll("%20", " ");
			//decodedString = decodedString.replaceAll("+", " ");
			System.out.println("HttpServerHandler.buildResponse(): Decoded string: " + decodedString);
			buffer = new DataInputStream(new FileInputStream(decodedString));
			mp3 = new byte[buffer.available()];
			buffer.readFully(mp3);

		}
		catch (FileNotFoundException e) 
		{
			e.printStackTrace();
		} catch (IOException e) 
		{
			e.printStackTrace();
		}
	}
}
